package com.myplaylist.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.myplaylist.model.Track;

public class PlaylistXMLParser extends DefaultHandler {
	
	private List<Track> trackList;
	
	public List<Track> processTrackList(File xmlFile) throws ParserConfigurationException, SAXException, IOException {
		
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser parser = spf.newSAXParser();
		
		parser.parse(xmlFile, this);
		
		
		return trackList;
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException, NumberFormatException, NullPointerException {
		if (qName.equals(Constants.XML_TRACKLIST)) {
			trackList = new ArrayList<Track>();
		} else if(qName.equals(Constants.XML_TRACKLIST_TRACK)) {
			Track tmp = new Track(attributes.getValue(Constants.XML_TRACKLIST_TRACK_TITLE), attributes.getValue(Constants.XML_TRACKLIST_TRACK_AUTHOR), Integer.parseInt(attributes.getValue(Constants.XML_TRACKLIST_TRACK_SCORE)));
			
			if (trackList != null) {
				trackList.add(tmp);
			} else {
				throw new NullPointerException("trackList is null");
			}
		}
	}
	
	
}
